import { Injectable } from '@nestjs/common'
import { MetaFileTreeDto } from './dto/meta-File-tree.dto'
import { DomainModel } from '@apps/meta/domain/model'
import { MetaFileTreeVo } from './vo/meta-file-tree.vo'
import { MetaFileDao } from '@apps/meta/domain/meta-file/meta-file.dao'

@Injectable()
export class MetaFileService {
  constructor(private readonly fileDao: MetaFileDao) {}

  /**
   * 获取文件树
   * @param param
   * @returns
   */
  async tree(param: MetaFileTreeDto) {
    const platformData = await this.fileDao.list({
      platform: param.platform,
      project: param.project,
      type: param.type,
      belong: DomainModel.MetaFileBelong.Platform,
    })
    const systemData = await this.fileDao.list({
      platform: param.platform,
      project: param.project,
      type: param.type,
      belong: DomainModel.MetaFileBelong.System,
    })

    const vos: MetaFileTreeVo[] = []
    const voMap = new Map<string, MetaFileTreeVo>()
    const eachData = (item: DomainModel.MetaFile) => {
      if (voMap.has(item.groupLabel)) {
        voMap.get(item.groupLabel)?.files.push(item)
      } else {
        const vo = new MetaFileTreeVo()
        vo.id = vos.length + 1
        vo.groupLabel = item.groupLabel
        vo.files = [item]

        voMap.set(item.groupLabel, vo)
        vos.push(vo)
      }
    }

    systemData.forEach(eachData)
    platformData.forEach(eachData)

    return vos
  }
}
